﻿/// <reference path="typings/swiper/swiper.d.ts" />
/// <reference path="typings/jquery/jquery.d.ts" />
/// <reference path="typings/knockout.mapping/knockout.mapping.d.ts" />
/// <reference path="ecatalog.api.ts" />

module Ecatalog {

    export class SizeViewModel {
        size: Ecatalog.Api.SizeDto = new Ecatalog.Api.SizeDto();
        selected: KnockoutObservable<boolean> = ko.observable(false);
        select: (data) => void;

        constructor(sizeDto: Ecatalog.Api.SizeDto, public selectedSizes: KnockoutObservableArray<Ecatalog.Api.SizeDto>) {

            this.size = sizeDto;
            var selectedSizes = this.selectedSizes();
            for (var i = 0; i < selectedSizes.length; i++) {
                var isModel = sizeDto.ModelId == selectedSizes[i].ModelId;
                var isSize = sizeDto.Value == selectedSizes[i].Value;
                if (isModel && isSize) {
                    this.selected(true);
                }
            }

            this.select = (data) => {
                var selected = this.selected();
                if (!selected) {
                    this.selectedSizes.push(data.size);
                } else {
                    var idx = this.selectedSizes.indexOf(data.size);
                    if (idx != -1) {
                        this.selectedSizes.splice(idx, 1);
                    }
                }
                this.selected(!selected);
            }
        }
    }

    export class Catalog {
        init: () => void;
        refresh: () => void;

        loadKits: (organizationId: number, numModel: string) => void;
        kits: KnockoutObservableArray<Ecatalog.Api.KitDto> = ko.observableArray([]);
        models: KnockoutObservableArray<Ecatalog.Api.ModelDto> = ko.observableArray([]);

        loadModelData: (modelId: number) => void;
        loadKitData: (kitId: number) => void;
        structures: KnockoutObservableArray<Ecatalog.Api.StructuresDto> = ko.observableArray([]);
        colors: KnockoutObservableArray<Ecatalog.Api.ColorsDto> = ko.observableArray([]);

        selectedSizes: KnockoutObservableArray<Ecatalog.Api.SizeDto> = ko.observableArray([]);
        sizes: KnockoutObservableArray<SizeViewModel> = ko.observableArray([]);
        description: KnockoutObservable<string> = ko.observable("");

        kitImageUrl: KnockoutObservable<string> = ko.observable("");
        shopMapUrl: KnockoutObservable<string> = ko.observable("");
        locationModel: KnockoutObservable<Ecatalog.Api.LocationDto> = ko.observable(null);
        locationComplect: KnockoutObservableArray<Ecatalog.Api.LocationDto> = ko.observableArray([]);
        costComplect: KnockoutObservable<number> = ko.observable(0);
        discountComplect: KnockoutObservable<number> = ko.observable(0);

        notSizeShopId: KnockoutObservable<number> = ko.observable(0);
        notSizeModelId: KnockoutObservable<number> = ko.observable(0);
        setActiveModels: (activeKitId: number) => void;
        setModels: (kitDtos: Ecatalog.Api.KitDto[]) => void;
        setNotifySize: (value: string) => void;
        notifySize: KnockoutObservable<string> = ko.observable("");
        showLocComplect: KnockoutObservable<boolean> = ko.observable(true);
        showModelLocation: () => void;
        showComplectLocation: () => void;
        activeModelId: KnockoutObservable<number> = ko.observable(0);

        kitSlidesPerView: number = 1;
        setKitSlidesPerView: (count: number) => void;

        constructor(target: HTMLElement) {

            this.setKitSlidesPerView = (count) => {
                if (count < 3) {
                    this.kitSlidesPerView = 1;
                } else {
                    this.kitSlidesPerView = 3;
                }

            }

            this.setNotifySize = (value) => {
                this.notifySize(value);
            }

            this.showModelLocation = () => {
                this.showLocComplect(false);
                this.refresh();
            }

            this.showComplectLocation = () => {
                this.showLocComplect(true);
                this.refresh();
            }

            this.refresh = () => {
                var locations = $("[name*='location-']");
                $.each(locations, function () {
                    var x = $(this).data("x");
                    var y = $(this).data("y");
                    $(this).css({
                        left: x + 'px',
                        top: y + 'px'
                    });
                });
            }

            this.init = () => {
                var self = this;

                function SetKitData(data: Swiper) {
                    var active = data.slides[data.activeIndex];
                    var imageUrl = $(active).attr("data-kitImage");
                    var costComplect = parseFloat($(active).attr("data-costComplect"));
                    var discountComplect = parseFloat($(active).attr("data-discountComplect"));
                    var kitid = parseInt($(active).attr("data-kitId"));

                    self.kitImageUrl(imageUrl);
                    self.costComplect(costComplect);
                    self.discountComplect(discountComplect);
                    self.loadKitData(kitid);
                }

                if (this.kitSlidesPerView == 1) {
                    var kitSwiper = new Swiper('#swiper-container-kitmodels', {
                        pagination: '.pagination-kit',
                        paginationClickable: false,
                        grabCursor: true,
                        slidesPerView: 1,
                        loop: false,
                        onTouchEnd: function (data) {
                            $('.wall').hide();
                            var active = data.slides[data.activeIndex];
                            var kitid = parseInt($(active).attr("data-kitId"));
                            self.kitImageUrl($(active).attr("data-kitImage"));
                            self.loadKitData(kitid);
                            self.setActiveModels(kitid);
                        },
                        onImagesReady: function (data) {
                            SetKitData(data);
                        }
                    });
                }
                else if (this.kitSlidesPerView == 3) {
                    var kitSwiper = new Swiper('#swiper-container-kitmodels', {
                        pagination: '.pagination-kit',
                        paginationClickable: false,
                        grabCursor: true,
                        slidesPerView: 3,
                        loop: false,
                        centeredSlides: true,
                        watchActiveIndex: true,
                        onTouchEnd: function (data) {
                            $('.wall').hide();
                            var active = data.slides[data.activeIndex];
                            var kitid = parseInt($(active).attr("data-kitId"));
                            self.kitImageUrl($(active).attr("data-kitImage"));
                            self.loadKitData(kitid);
                            self.setActiveModels(kitid);
                        },
                        onImagesReady: function (data) {
                            SetKitData(data);
                        }
                    });
                }


                $(".swiper-kitmodels").each(function (index, elem) {
                    var count = parseInt($(elem).attr("data-count"));
                    var pag = '.p-' + $(elem).attr("id");

                    if (count < 3) {                       
                        var mySwiper = new Swiper($(this)[0], {
                            pagination: pag,
                            paginationClickable: false,
                            grabCursor: true,
                            slidesPerView: 1,
                            loop: false,
                            onTouchEnd: function (data) {
                                var active = data.slides[data.activeIndex];
                                var modelId = parseInt($(active).attr("data-modelId"));
                                self.loadModelData(modelId);
                            },
                            onImagesReady: function (data) {
                                var active = data.slides[data.activeIndex];
                                for (var i = 0; i < data.slides.length; i++) {
                                    var modelId = parseInt($(data.slides[i]).attr("data-modelId"));
                                    if (self.activeModelId() == modelId) {
                                        self.notSizeModelId(modelId);
                                        mySwiper.swipeTo(i - 1);
                                        self.loadModelData(modelId);
                                        break;
                                    };
                                }
                            }
                        });
                    }
                    else {                       
                        var mySwiper = new Swiper($(this)[0], {
                            pagination: pag,
                            paginationClickable: false,
                            grabCursor: true,
                            slidesPerView: 3,
                            loop: false,    
                            centeredSlides: true,
                            watchActiveIndex: true,                        
                            onTouchEnd: function (data) {
                                var active = data.slides[data.activeIndex];
                                var modelId = parseInt($(active).attr("data-modelId"));
                                self.loadModelData(modelId);
                            },
                            onImagesReady: function (data) {
                                var active = data.slides[data.activeIndex];
                                for (var i = 0; i < data.slides.length; i++) {
                                    var modelId = parseInt($(data.slides[i]).attr("data-modelId"));
                                    if (self.activeModelId() == modelId) {
                                        self.notSizeModelId(modelId);
                                        mySwiper.swipeTo(i - 1);
                                        self.loadModelData(modelId);
                                        break;
                                    };
                                }
                            }
                        });
                    }
                });
            }

            this.setModels = (kitDtos) => {
                for (var i = 0; i < kitDtos.length; i++) {
                    for (var j = 0; j < kitDtos[i].ModelDtos.length; j++) {
                        this.models.push(kitDtos[i].ModelDtos[j]);
                    }
                }
            }

            this.setActiveModels = (activeKitId) => {
                $(".swiper-kitmodels").hide();
                $(".pagination-kit-models").hide();
                var selector = "kit-" + activeKitId;
                $("#" + selector).show();
                $(".p-" + selector).show();
                //получаю id отображаемой модели
                var modelId = $("#kit-" + activeKitId)
                    .find(".swiper-wrapper")
                    .find(".swiper-slide-active")
                //.next(".swiper-slide")                    
                    .attr("data-modelId");
                this.loadModelData(parseInt(modelId));
            }

            this.loadModelData = (modelId) => {
                var m = this.models();
                for (var i = 0; i < m.length; i++) {
                    if (m[i].ModelId == modelId) {
                        this.notSizeModelId(m[i].ModelId);
                        this.structures(m[i].StructuresDtos);
                        this.colors(m[i].ColorsDtos);
                        var arr = [];
                        var ms = m[i].SizeDtos;
                        for (var j = 0; j < ms.length; j++) {
                            var vm = new SizeViewModel(ms[j], this.selectedSizes);
                            arr.push(vm);
                        }
                        this.sizes(arr);
                        this.description(m[i].Description);
                        this.locationModel(m[i].LocationDto);
                        this.refresh()
                        break;
                    }
                }
            }

            this.loadKitData = (kitid) => {
                var k = this.kits();
                for (var i = 0; i < k.length; i++) {
                    if (k[i].KitId == kitid) {
                        this.locationComplect(k[i].LocationDtos);
                        this.discountComplect(k[i].DiscountComplect);
                        this.costComplect(k[i].CostComplect);
                        this.refresh();
                        break;
                    }
                }
            }

            this.loadKits = (organizationId, numModel) => {
                var params = new Ecatalog.Api.GetComplectsParams();
                params.NumModel = numModel;
                params.OrganizationId = organizationId;
                Ecatalog.Api.AsyncClient.Current.GetComplects(params, (result) => {
                    if (result != null) {
                        this.setKitSlidesPerView(result.KitDtos.length);
                        this.activeModelId(result.ActiveModelId);
                        this.notSizeModelId(result.ActiveModelId);
                        this.notSizeShopId(result.ShopId);
                        this.kits(result.KitDtos);
                        this.setModels(result.KitDtos);
                        this.shopMapUrl(result.ShopMapUrl);
                        this.init();
                        var selector = "kit-" + result.ActiveKitId;
                        $(".pagination-kit-models").hide();
                        $("#" + selector).show();
                        $(".p-" + selector).show();
                    }
                });
            }
            ko.applyBindings(this, target);
        }
    }
}

$(document).ready(() => {
    var catalogElem = $("[data-catalog='true']");
    if (catalogElem.length > 0) {
        var ecatalog = new Ecatalog.Catalog(catalogElem[0]);
        var organizationId = $("#OrganizationId").val();
        var numModel = $("#NumModel").val();
        ecatalog.loadKits(organizationId, numModel);
    }
});


